import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, TextInput,
	PixelRatio, Platform, ScrollView, Modal, FlatList, Alert
} from 'react-native';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import HTTP from '../../../utils/http';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import { BoxShadow } from 'react-native-shadow';

const scale = GLOBAL.SCALE;
const shadowOpt = {
	width: GLOBAL.SCREEN_WIDTH,
	height: 223 * scale,
	color: "#000",//阴影颜色
	border: 6 * scale,//阴影宽度
	radius: 0 * scale,//包裹的子元素圆角多少这里必须是多少
	opacity: 0.1,//透明度
	x: 0,
	y: 0,
}
export default class SelectComponent extends Component {

	/* 
	属性： 
		modalVisible:显示,
		'false' 多选, 字符串
		sendData:{companyId:'',companyName:''}
		mainCheckData:[{goodsId:'',goodsName:''}]  //数据回显
	方法：
		cancelPress()   取消按钮回调
		confirmPress()  确定按钮回调
	*/

	constructor(props) {
		super(props);
		console.log(' this.props', this.props)
		let { modalVisible, mainCheckData } = this.props;
		this.state = {
			modalVisible: true,
			sideDataSource: [], // 一级数据
			mainDataSource: [], // 二级数据
			sideCheckData: [], // 一级数据回显
			mainCheckData: mainCheckData || [],   // 二级数据回显
			status: 'data',  // 数据加载状态
		}
		this.reportsList = this.props.sendData || [];
		console.log('selectcomponent-report', this.reportsList);
	}

	componentWillMount () {
		this._init();
	}

	// 初始  获取数据 且初始化
	_init = async () => {
		//获取数据
		// let goodsData = await this._getGoodsData();
		//根据数据初始化
		this._formattingData(this.reportsList);
	}

	componentWillReceiveProps (props) {
		let { modalVisible } = props;
		this.setState({
			modalVisible
		}, () => {
			this._init();
		})
	}

	// 获取商品数据
	_getGoodsData = async () => {
		if (this.sendData.goodsName == '') {
			delete this.sendData.goodsName;
		}
		let url = '';
		let responseData = await HTTP.POST(API_GENERATE(url), this.sendData);
		this.setState({
			status: responseData && responseData.length > 0 ? 'data' : 'empty'
		})
		return responseData || [];
	}

	// 数据格式化
	_formattingData = (data, onoff) => {
		let { mainCheckData, sideCheckData, sideDataSource, mainDataSource } = this.state;
		//处理初始化的数据
		mainCheckData = mainCheckData && mainCheckData.filter((item) => {
			if (item.typeId) {
				return item;
			}
		})
		let indexArr = -1;
		if (mainCheckData.length > 0 && !onoff) {  // 回显
			data && data.map((item, index1) => {
				item.index = 1;    // --------------------
				item.children && item.children.map((items, index2) => {  // 二级
					if (items.typeId == mainCheckData[1].typeId) { // 
						items.selected = true;
						indexArr = index1;
						item.index++;  // ---------------
					} else {
						items.selected = false;
					}
					return items
				})
				return item
			})

			data && data.map((item, index1) => {
				if (index1 == indexArr) {
					item.selected = true;
					mainDataSource = item.children;
				} else {
					item.selected = false;
				}
			})
		} else {  // 第一个是收藏，默认显示第二个
			data && data.map((item, index) => {
				if (index == 1) {
					item.selected = true;
					mainDataSource = item.children;
					sideCheckData.push({ typeId: item.typeId, typeName: item.typeName });
				} else {
					item.selected = false;
				}
				item.index = 0;    // --------------------
				return item;
			})
		}
		sideDataSource = data;
		this.setState({
			sideDataSource,
			mainDataSource
		})
	}

	// 一级勾选
	_sideCheckFn = (typeId) => {
		let { sideDataSource, mainDataSource, sideCheckData } = this.state;
		sideDataSource && sideDataSource.map((item) => {
			if (item.typeId == typeId) {
				sideCheckData[0] = { typeId: item.typeId, typeName: item.typeName };
				item.selected = true;
				mainDataSource = item.children;
			} else {
				item.selected = false;
			}
			return item;
		})
		this.setState({
			sideDataSource,
			mainDataSource,
			sideCheckData
		})
	}

	// 二级勾选  [{goodsId:'1',goodsName:'阿三'}]
	_mainCheckFn = (rptId, rptName, isExpired, itemId, rptItem) => {
		let { mainCheckData, sideCheckData, sideDataSource } = this.state;
		let isRemove = mainCheckData && mainCheckData.some((item) => {
			return item.typeId == rptId
		})

		if (isRemove) {  // 移除
			mainCheckData = [];
			//sideCheckData = [];
		} else {  // 添加
			mainCheckData[0] = { rptId: rptId, rptName: rptName, isExpired, itemId, rptItem };
		}
		if (mainCheckData.length == 0) {
			sideDataSource && sideDataSource.map((item) => {
				item.index = 0;
				item.children && item.children.map((items) => {
					items.selected = false;
					return items;
				})
			})
		} else {
			sideDataSource && sideDataSource.map((item) => {
				item.index = 0;
				item.children && item.children.map((items) => {
					let lsOnoff = mainCheckData && mainCheckData.some((a) => {
						return a.rptId == items.rptId
					})
					if (lsOnoff) {
						items.selected = true;
						item.index++;   ///  --------------------------
						return items;
					} else {
						items.selected = false;
						return items;
					}
				})
				return item;
			})
		}
		this.setState({
			sideDataSource,
			mainCheckData,
			//sideCheckData
		})

		//选中即确定
		this._confirmPress();
	}

	// 确定按钮
	_confirmPress = () => {
		let { mainCheckData } = this.state;
		this.setState({
			modalVisible: false
		}, () => {
			this.props.confirmPress && this.props.confirmPress(mainCheckData);
			this.sendData = this.props.sendData;
		})
	}

	// 取消按钮
	_cancelPress = () => {
		let { mainCheckData } = this.state;
		this.setState({
			modalVisible: false
		}, () => {
			this.props.cancelPress && this.props.cancelPress(mainCheckData);
			this.sendData = this.props.sendData;
		})
	}

	//二级数据
	_renderMain = (data) => {
		const { rptName, rptId, selected, isExpired, itemId, attentionFlag } = data.item;
		// let optionPicSourse = require('../../../imgs/global/option.png');
		// let selectedPicSourse = require('../../../imgs/global/success.png');
		// let fluidPicSourse = require('../../../imgs/order/fluid.png');
		const starYellew = require('../../../imgs/report/starYellow.png');
		const starEmpty = require('../../../imgs/report/starYellowEmpty.png');

		let collectSource = attentionFlag ? starYellew : starEmpty;
		// let picSource = selected ? selectedPicSourse : optionPicSourse;
		return (
			<TouchableOpacity onPress={() => {
				this._mainCheckFn(rptId, rptName, isExpired, itemId, data.item);
			}} activeOpacity={0.5} style={styles.listMainRow}>
				<Text style={[styles.listSideText, styles.longText]}>
					{rptName}
				</Text>
				<Image source={collectSource} style={styles.optionPic} />
				{/* <Image source={picSource} style={styles.optionPic} /> */}
			</TouchableOpacity>
		);
	}

	//一级数据
	_renderSide = (side) => {
		let { typeName, typeId, children, selected, index } = side.item;
		let curStyle = (selected) ? styles.listSideRowCur : null;
		return (
			<TouchableOpacity onPress={() => { this._sideCheckFn(typeId, children); }} activeOpacity={0.5} style={[styles.listSideRow, curStyle]}>
				<Text style={styles.listSideText}>{typeName}</Text>
			</TouchableOpacity>
		);
	}

	render () {
		let { modalVisible, sideDataSource, mainDataSource, status } = this.state;
		return (
			<View style={styles.containerModal}>
				<TouchableOpacity style={styles.containerBg} onPress={() => { this._cancelPress() }}></TouchableOpacity>
				<BoxShadow setting={shadowOpt}>
					<View style={styles.listCell}>
						{/* <View style={styles.listHead}>
								<TouchableOpacity onPress={() => { this._cancelPress() }} activeOpacity={0.5}>
									<Text style={styles.listHeadText}>取消</Text>
								</TouchableOpacity>
								<Text style={[styles.listHeadText, { fontSize: 14 * scale, color: '#404040' }]}>请选择报表</Text>
								<TouchableOpacity onPress={() => { this._confirmPress() }} activeOpacity={0.5}><Text style={styles.listHeadText}>确定</Text>
								</TouchableOpacity>
							</View> */}
						<View style={styles.listView}>
							{sideDataSource && sideDataSource.length > 0 ? (
								<View style={{ flex: 1, flexDirection: 'row' }}>
									<View style={styles.listSideWrap}>
										<FlatList
											extraData={this.state}
											style={styles.listSideView}
											data={sideDataSource}
											renderItem={this._renderSide}
										/>
									</View>
									<ScrollView
										horizontal={true}
										style={styles.listMainWrap}
									>
										{
											mainDataSource && mainDataSource.length > 0 ? (
												<FlatList
													extraData={this.state}
													style={styles.listMainView}
													data={mainDataSource}
													renderItem={this._renderMain}
												/>
											) : (
													<View style={{ width: 255 * scale }}>
														<PageStatusIndex status={'empty'} emptyText={'该类目暂时无报表'} />
													</View>
												)
										}
									</ScrollView>
								</View>
							) : (<PageStatusIndex status={status} emptyText={'暂无报表'} />)}
						</View>
					</View>
				</BoxShadow>
			</View>
		);
	}

}


const styles = StyleSheet.create({
	containerModal: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		// backgroundColor: 'rgba(0, 0, 0, .05)',
		justifyContent: 'flex-start'
	},
	containerBg: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		position: 'absolute',
		top: 0
	},
	listHead: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		height: 52 * scale,
		width: 375 * scale,
		alignItems: 'center',
	},
	listHeadText: {
		fontSize: 16 * scale,
		color: style.color.themeColor,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 8 * scale,
		paddingRight: 8 * scale
	},
	listCell: {
		backgroundColor: '#fff',
		width: 375 * scale,
		height: 223 * scale,
	},
	listView: {
		flex: 1,
		flexDirection: 'row',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	listSideWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#F8F8F8',
	},
	listSideView: {
		width: 120 * scale,
	},
	listSideRow: {
		height: 40 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		flexDirection: 'row'
	},
	listSideRowCur: {
		backgroundColor: '#fff',
	},
	listSideText: {
		fontSize: 13 * scale,
		color: '#8B8B8B',
	},
	longText: {
		fontSize: 13 * scale,
		color: '#8B8B8B',
		width: 160 * scale
	},
	listMainWrap: {
		paddingBottom: 20 * scale,
		backgroundColor: '#fff',
		width: 255 * scale,
	},
	listMainView: {
		width: 255 * scale,
		paddingLeft: 2 * scale,
		paddingRight: 20 * scale,
		backgroundColor: '#fff'
	},
	listMainRow: {
		alignItems: 'center',
		flexDirection: 'row',
		justifyContent: 'space-between',
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale
	},
	optionPic: {
		width: 14 * scale,
		height: 14 * scale,
		marginRight: 1 * scale
	},
	searchBox: {
		height: 45 * scale,
		paddingLeft: 15 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 7 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	searchBg: {
		width: 300 * scale,
		height: 30 * scale,
		backgroundColor: style.color.light,
		borderRadius: 4 * scale,
		flexDirection: 'row',
		alignItems: 'center',
	},
	searchBtn: {
		fontSize: 16 * scale,
		color: style.color.dark,
		marginLeft: 10 * scale,
		padding: 5 * scale
	},
	searchImg: {
		width: 12 * scale,
		height: 11 * scale,
		marginLeft: 20 * scale,
		marginRight: 20 * scale
	},
	searcuhInput: {
		width: 200 * scale,
		paddingVertical: 0,
		height: 18 * scale
	},
	selectNumber: {
		borderRadius: 5 * scale,
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
		fontSize: 11 * scale,
		backgroundColor: style.color.themeColor,
		color: style.color.white,
		textAlign: 'center'
	},
	tips: {
		width: 15 * scale,
		height: 15 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderRadius: 2 * scale,

	},
	tipsText: {
		fontSize: 10 * scale
	}
})